﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Infrastructure.IOC;
using WCS.Infrastructure.Tools;
using WCS.Service.Interface;

namespace WCS.Service.Instance
{
    [Inject]
    public class EpaylinksPayService : BaseService, IEpaylinksPayService
    {
        private readonly IConfiguration _configuration;
        private readonly IHttpContextAccessor _httpContextAccessor;

        //商户私钥路径，密码，易票联公钥路径，
        public const string privateKey_path = "D:\\\\certs\\\\test\\\\user.pfx";
        public const string key_password = "123456";
        public const string publicKey_path = "D:\\\\certs\\\\test\\\\efps.cer"; 

        public EpaylinksPayService(IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            _configuration = configuration;
            _httpContextAccessor = httpContextAccessor;

        }

        /// <summary>
        /// 测试易票联接口
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> Test()
        {
            Console.WriteLine("易票联接口测试");
            //测试证书签名
            string data = "123";//测试数据，将来会是接口传递的对象转换成json字符串
            string sign = EncryptionUtility.RSACryption.RSASign(data, key_password, privateKey_path);//使用商户私钥签名
            Console.WriteLine("测试签名：" + sign);
            //测试验签,使用易票联公钥验签易票联返回
            Console.WriteLine(EncryptionUtility.RSACryption.verifySign("{\"returnCode\":\"0000\",\"returnMsg\":\"Success\",\"nonceStr\":\"13e1befb0f324fe0ba5cc085ed49bd49\",\"casherUrl\":\"http://test-efps.epaylinks.cn/api/cash/cashier?token=1faf75eea5db4fda90fc8cdee798d2fe\",\"orderToken\":\"1faf75eea5db4fda90fc8cdee798d2fe\",\"outTradeNo\":\"20220927175758405\"}", "iZKTL9WLHnaJAAi1ndsx3McXhIx9dBMj7b6eVWYIgUVhik1qt0mOjp1FzlD73frR2qy7js0RmychE5N/kKgDJYgeQ/gkdulwsR61jJ+T0djLkosuvdZ/h/GbLf7pHGlbtw+Uuo0BjbzYWtV0fi1glkKhnzwUOklFxcjiR0r6bistwSne4ts5PBQtluNXiNnddcGtsW71CG2R4LBHXpxYdlrilq7uwbjuQRLNJrZkEj9dWtf5gYiU//WbM0qwJEDWOz5TliF5ATBYW0AnXxvSyLKP+UxcZQTHXvRHWPjaJ+1x5REeV0Vath4OgclHHgAKlNvMF/dRGb28ZG97NRz9AA==", publicKey_path));

            //测试发送数据，统一下单接口
            //Program pg = new Program();
            //pg.unifiedPayment();
            //unifiedPayment();

            //测试提现、代付接口
            // pg.withdrawalToCard();
            //withdrawalToCard();

            return GetResult(1);
        }

        /// <summary>
        /// 统一下单测试
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> UnifiedPaymentTest()
        {
            Console.WriteLine("---------------------测试统一下单-----------------------");
            string url = "https://test-efps.epaylinks.cn/api/txs/pay/UnifiedPayment";
            //订单号每次都需要更换
            string sentent = "{\"areaInfo\":\"440106\",\"attachData\":\"planguid\",\"clientIp\":\"127.0.0.1\",\"customerCode\":\"562265003122220\",\"needSplit\":false,\"noCreditCards\":false,\"nonceStr\":\"14c6752e2620464eba0a1f51e09bdec1\",\"notifyUrl\":\"http://www.baidu.com\",\"orderInfo\":{\"businessType\":\"test\",\"goodsList\":[{\"amount\":1,\"name\":\"123\",\"number\":\"1...\"}],\"id\":\"test\"}," +
                "\"payAmount\":2,\"payCurrency\":\"CNY\",\"redirectUrl\":\"\",\"transactionEndTime\":\"\"," +
                "\"version\":\"3.0\",";

            string dt = DateTime.Now.ToString("yyyyMMddHHmmss");
            string outTradeNo = dt;
            string transactionStartTime = dt;
            string sentence = sentent + "\"outTradeNo\":\"" + outTradeNo + "\",\"transactionStartTime\":\"" + transactionStartTime + "\"}";

            System.Console.WriteLine("接口传递参数:" + sentence);
            var result =await this.post(sentence, url);

            return GetResult(1);
        }

        /// <summary>
        /// 提现代付测试
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> WithdrawalToCardTest()
        {
            Console.WriteLine("---------------------测试提现-----------------------");
            string url = "https://test-efps.epaylinks.cn/api/txs/pay/withdrawalToCard";

            //订单号每次都需要更换
            string sentent = "{\"amount\":100,\"bankAccountType\":\"2\",\"bankCity\":\"广州市\",\"bankName\":\"招商银行\",\"bankProvince\":\"广东省\",\"bankSub\":\"广州支行\",\"customerCode\":\"562265003122220\",\"isAdvanceFund\":\"\",\"isFullAmount\":0,\"nonceStr\":\"aabb5691afc44d809ff09999996d2f4a\",\"notifyUrl\":\"http://172.20.18.116:8080/demo/notify/WithdrawalForSubMerchant\"," +
                "\"payCurrency\":\"CNY\",\"remark\":\"这是附言\",";

            string dt = DateTime.Now.ToString("yyyyMMddHHmmss");
            string outTradeNo = dt;
            //加密卡号姓名
            string bankUserName = EncryptionUtility.RSACryption.RSAEncrypt("哎哎哎", publicKey_path);
            string bankCardNo = EncryptionUtility.RSACryption.RSAEncrypt("6214830201234567", publicKey_path);
            string sentence = sentent + "\"outTradeNo\":\"" + outTradeNo + "\",\"bankUserName\":\"" + bankUserName + "\",\"bankCardNo\":\"" + bankCardNo + "\"}";
            
            System.Console.WriteLine("接口传递参数:" + sentence);
            var result = await this.post(sentence, url);

            return GetResult(1);
        }


        public async Task<ApiResult> post(string sentence, string url)
        {

            Encoding encoding = Encoding.GetEncoding("UTF-8");
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            // 准备请求,设置参数
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Headers.Set("x-efps-sign-type", "SHA256withRSA");
            request.Headers.Set("x-efps-sign-no", "562265003122220003");
            request.Headers.Set("x-efps-sign", EncryptionUtility.RSACryption.RSASign(sentence, key_password, privateKey_path));
            request.Headers.Set("x-efps-timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));

            byte[] data = encoding.GetBytes(sentence);
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Flush();
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            //获取返回签名
            string response_sign = response.GetResponseHeader("x-efps-sign");
            sr = new StreamReader(instream, encoding);
            //返回结果代码
            string content = sr.ReadToEnd();
            Console.WriteLine("返回参数：" + content);
            //验签返回:
            //Console.WriteLine("验签结果：" + RSACryption.verifySign(content, response_sign, publicKey_path));
            var result = EncryptionUtility.RSACryption.verifySign(content, response_sign, publicKey_path);
            return GetResult(1, data: new
            {
                content,
                result
            });
        }

       
    }
}
